#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <cstring>

class Task_Add
{
public:
    Task_Add(int a, int b) :_a(a), _b(b)
    {}
    int Excute() { return _a + _b; }
    ~Task_Add(){}
private:
    int _a;
    int _b;
};

class Result
{
public:
    Result(int result) :_result(result)
    {}
    int GetResult(){ return _result; }
    ~Result(){}
private:
    int _result;
};

// void* ThreadRun(void* args)
// {
//     std::string name = static_cast<const char*>(args);
//     for(int i = 0; i < 5; i++)
//     {
//         // std::cout << "[pid=" << getpid() << "]线程[" << name << "]正在运行..." << std::endl;
//         printf("[pid=%d]线程[%s]正在运行...\n", getpid(), name.c_str());
//         sleep(2);
//     }
//     return (void*)10;
// }

void* ThreadRun(void* args)
{
    // pthread_detach(pthread_self());
    Task_Add* task = static_cast<Task_Add*>(args);
    Result* res = new Result(task->Excute());
    return (void*)res;
}

int main()
{
    pthread_t tid;
    // pthread_create(&tid, nullptr, ThreadRun, (void*)"thread-1");
    Task_Add task(10, 20);
    pthread_create(&tid, nullptr, ThreadRun, (void*)&task);

    // 分离之后的线程不能被等待
    // pthread_detach(tid);
    // for(int i = 0; i < 10; i++)
    // {
    //     // std::cout << "[pid=" << getpid() << "]主线程正在运行..." << std::endl;
    //     printf("[pid=%d]主线程正在运行...\n", getpid());
    //     sleep(2);
    // }

    Result* ret = nullptr;
    // sleep(1);
    int n = pthread_join(tid, (void**)&ret);
    if(n != 0)
    {
        std::cout << "等待子进程失败: " << strerror(n) << std::endl;
    }
    std::cout << "子进程结果: " << ret->GetResult() << std::endl;
    delete ret;
    return 0;
}